<template>
    <el-row class="padd20 bgf main-cont">
        <el-col class="posa" style="height: 100%;">
            <el-col class="btn">
                <el-col class="padd20" style="height: 700px;">
                    <el-form ref="lineForm" :rules="rules" :model="lineForm" label-width="110px" class="reset-form">
                        <el-col :span="11">
                            <el-col>
                                <el-form-item label="标题" prop="name">
                                    <el-input v-model="lineForm.name" class="text"></el-input>
                                </el-form-item>
                                <el-form-item label="劳动分类" prop="ldfl">
                                    <el-select v-model="lineForm.ldfl" placeholder="请选择" class="text">
                                        <el-option label="日常生活劳动" value="0"></el-option>
                                        <el-option label="生产劳动" value="1"></el-option>
                                        <el-option label="服务性劳动" value="2"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="实践封面" prop="sjImage" ref="sjImage">
                                    <el-col class="box box-align-end box-pack-start">
                                        <el-col>
                                            <el-upload class="avatar-uploader" :action="uploadfileurlSj"
                                                :show-file-list="false" :limit="1" accept=".jpg,.png,.jpeg"
                                                :on-progress="progressSj" :on-success="successSj"
                                                :before-upload="beforeUploadSj">
                                                <!-- <img v-if="lineForm.sjImage" :src="lineForm.sjImage" class="avatar"> -->
                                                <el-image v-if="lineForm.sjImage" :src="lineForm.sjImage" class="avatar"
                                                    fit="cover"></el-image>
                                                <div v-else class="upload-icon">
                                                    <i class="el-icon-upload"></i>
                                                    <div>上传</div>
                                                </div>
                                            </el-upload>
                                            <el-progress v-if="showProgressSj" :percentage="progIntSj"></el-progress>
                                        </el-col>
                                        <el-col>
                                            <el-button type='text' @click="dialogVisible = true">选择系统封面</el-button>
                                        </el-col>
                                    </el-col>


                                </el-form-item>
                                <el-form-item label="实践视频" ref="image">
                                    <el-image v-if="lineForm.sjVideoImage" :src="lineForm.sjVideoImage" class="avatar"
                                        fit="cover" @click="showVideo(lineForm.url)"></el-image>
                                    <div class="box ">

                                        <el-upload class="avatar-uploader mr10" :action="uploadfileurl"
                                            :show-file-list="false" accept=".mp4" :on-progress="progress"
                                            :on-success="success" :before-upload="beforeUpload"
                                            v-if="maxRole=='team' || maxRole=='jyzz' || maxRole=='jyy'">
                                            <div class=" box box-tb box-pack-start">

                                                <el-button style="width: 70px;" class="mb20">上传</el-button>
                                            </div>
                                        </el-upload>
                                        <el-button @click="showVideo(lineForm.url)" v-if="lineForm.url !=null">查看
                                        </el-button>
                                    </div>

                                    <!-- <div v-else>{{lineForm.fileName}}</div> -->

                                    <el-progress v-if="showProgress" :percentage="progInt"></el-progress>
                                </el-form-item>
                                <el-form-item label="劳动目标" prop="">
                                    <el-input type="textarea" placeholder="" v-model="lineForm.ldmb"></el-input>
                                </el-form-item>
                                <el-form-item label="场所与工具" prop="">
                                    <el-input type="textarea" placeholder="" v-model="lineForm.csygj"></el-input>
                                </el-form-item>
                                <el-form-item label="劳动安全与规则" prop="">
                                    <el-input type="textarea" placeholder="" v-model="lineForm.aqygz"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col>
                                <el-form-item label="组织准备" prop="">
                                    <el-input type="textarea" placeholder="" v-model="lineForm.zzzb"></el-input>
                                </el-form-item>
                                <el-form-item label="具体流程" prop="">
                                    <el-input type="textarea" placeholder="" v-model="lineForm.jtly"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-col>
                        <el-dialog title="选择系统封面" :visible.sync="dialogVisible" width="600px"
                            @close="dialogVisible = false" :center="false">
                            <el-col class="fm">
                                <el-image :src="item.url" v-for="(item,index) in imageUrls" :key="index"
                                    class="mr10 mb5 cp img" :class="{active:current == index}"
                                    @click="changeFm(item,index)"></el-image>
                            </el-col>
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="dialogVisible = false">取 消</el-button>
                                <el-button type="primary" @click="confirm()">确 定</el-button>
                            </span>
                        </el-dialog>
                        <el-col :span="10" style="margin-left: 50px;">
                            <el-col class="tl">
                                <div class="title">
                                    评价标准（{{totalScore}}分）
                                </div>
                            </el-col>
                            <el-col>
                                <el-form-item v-for="(domain, index) in lineForm.domains" :label="''+(index+1)"
                                    :key="index" :prop="'domains.' + index + '.cont'" :rules="{
                                      required: true, message: '请填写评分标准', trigger: 'blur'
                                    }" class="item">
                                    <el-input v-model="domain.cont" class="text"></el-input>
                                    <el-input-number v-model="domain.score" controls-position="right" :min="1"
                                        :max="100" class="mr20 ml20" @change="resetScore()"></el-input-number>
                                    分
                                    <el-button @click.prevent="removeDomain(domain)" class="ml10 reset-cancel-btn"
                                        v-if="maxRole=='team' || maxRole=='admin'">
                                        删除
                                    </el-button>
                                </el-form-item>
                                <el-form-item>
                                    <el-button @click="addDomain" class="">+添加</el-button>
                                </el-form-item>
                                <el-form-item class="submit">
                                    <el-button class="reset-cancel-btn" @click="handleClose('lineForm')">返 回</el-button>
                                    <el-button class="reset-comfirm-btn" @click="onSubmit('lineForm')">
                                        保 存</el-button>
                                </el-form-item>
                            </el-col>
                        </el-col>
                    </el-form>
                </el-col>
            </el-col>
        </el-col>
    </el-row>
</template>

<script>
    export default {
        props: {
            sj: {
                type: Object
            }
        },
        data() {
            return {
                tip: "创建劳动实践",
                loginInfo: this.$store.state.loginInfo,
                jyzid: this.$store.state.jyzid,
                totalScore: 0,
                imageUrls: [{
                        url: 'https://yh-sys.oss-cn-beijing.aliyuncs.com/39D167590DD64F1B9627575F3506F6C4fm%20%281%29.png?Expires=4804581082&OSSAccessKeyId=LTAI4GL8SwAiLh3sSPXDS7z9&Signature=Px94t8QywxWuJzoSVTB6tyMjubk%3D'
                    },
                    {
                        url: 'https://yh-sys.oss-cn-beijing.aliyuncs.com/F1A6D7AB73BE4350877D28AB6E2F0252fm%20%282%29.png?Expires=4804581129&OSSAccessKeyId=LTAI4GL8SwAiLh3sSPXDS7z9&Signature=nHf3%2FS1mpKtphg4R%2FJ2oNUJDYZk%3D'
                    },
                    {
                        url: 'https://yh-sys.oss-cn-beijing.aliyuncs.com/54796B2516F54BCBAE3A15D11A8A388D%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20220426215133.jpg?Expires=4804581168&OSSAccessKeyId=LTAI4GL8SwAiLh3sSPXDS7z9&Signature=TWKWn06Cp3n%2BwImWxlueHVCrJR4%3D'
                    },
                    {
                        url: 'https://yh-sys.oss-cn-beijing.aliyuncs.com/3281C369149248CA8433DCFBBB820153%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20220426215144.jpg?Expires=4804581179&OSSAccessKeyId=LTAI4GL8SwAiLh3sSPXDS7z9&Signature=gWtMTX%2BqNFiltY4K9Nxc46Q%2B8IA%3D'
                    }
                ],
                lineForm: {
                    url: '',
                    id: '',
                    name: '',
                    ldfl: '',
                    img: '',
                    fileName: '',
                    fileid: '',
                    ldmb: '',
                    csygj: '',
                    aqygz: '',
                    zzzb: '',
                    jtly: '',
                    domains: [{
                        cont: '',
                        score: 0
                    }],
                    sjImage: '',
                    sjVideoImage: ''
                },
                rules: {
                    name: [{
                        required: true,
                        message: '请输入标题',
                        trigger: 'blur'
                    }],
                    ldfl: [{
                        required: true,
                        message: '请选择劳动分类',
                        trigger: 'change'
                    }],
                    sjImage: [{
                        required: true,
                        message: '请上传封面',
                        trigger: 'change'
                    }],
                },
                showProgress: false,
                showProgressSj: false,
                progInt: 0,
                progIntSj: 0,
                uploadfileurl: this.$url.baseURL + '/upload/uploadfile',
                uploadfileurlSj: this.$url.baseURL + '/upload/uploadfile',
                dialogVisible: false,
                current: 0,
                diaImg: '',
                maxRole: this.$store.state.maxRole,
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.getEditData();
            })
        },
        methods: {
            changeFm(item, index) {
                this.current = index;
                this.diaImg = item.url
                this.$refs['sjImage'].clearValidate()
            },

            confirm() {
                this.dialogVisible = false
                this.lineForm.sjImage = this.diaImg
            },
            showVideo(url) {
                window.open(url);
            },
            //获取编辑数据
            getEditData() {
                this.$nextTick(() => {
                    this.lineForm.id = this.sj.id,
                        this.lineForm.url = this.sj.url,
                        this.lineForm.name = this.sj.title,
                        this.lineForm.ldfl = this.sj.typeId != undefined ? this.sj.typeId.toString() : 0,
                        this.lineForm.sjImage = this.sj.img,
                        this.lineForm.fileName = this.sj.fileName,
                        this.lineForm.fileid = this.sj.fileid,
                        this.lineForm.ldmb = this.sj.ldmb,
                        this.lineForm.csygj = this.sj.csygj,
                        this.lineForm.aqygz = this.sj.aqygz,
                        this.lineForm.zzzb = this.sj.zzzb,
                        this.lineForm.jtly = this.sj.jtly,
                        this.lineForm.domains = this.sj.pfbzs
                    this.resetScore()
                })

            },
            resetScore() {
                if (this.lineForm.domains != undefined) {
                    this.totalScore = 0
                    let score = this.lineForm.domains.map(res => {
                        return res.score
                    })
                    score.forEach(res => {
                        this.totalScore = this.totalScore + res
                    })
                }
            },
            removeDomain(item) {
                var index = this.lineForm.domains.indexOf(item)
                var len = this.lineForm.domains.length
                if (len !== 1) {
                    this.lineForm.domains.splice(index, 1)
                }
                this.resetScore()
            },
            addDomain() {
                this.lineForm.domains.push({
                    cont: '',
                    score: 0,
                });
                this.resetScore()
            },
            handleClose(formName) {
                this.$refs[formName].resetFields();
                this.$router.go(-1)
            },
            progressSj(event) {
                this.showProgressSj = true;
                this.progInt = parseInt(event.loaded / event.total * 100, 10);
            },
            successSj(response, file, fileList) {
                this.showProgressSj = false;
                this.lineForm.sjImage = response.body.data.url;
                this.$refs['sjImage'].clearValidate()
            },
            beforeUploadSj(file) {
                const fileName = file.name;
                const index = fileName.lastIndexOf(".");
                const ext = fileName.substr(index + 1);
                const arr = ["jpg", "png", "jpeg"];
                const isOk = arr.includes(ext);
                if (!isOk) {
                    this.$message.warning('封面格式暂不支持！');
                    return false;
                }
                var imgSize = file.size / (1024 * 1024);
                if (imgSize > 50) {
                    this.$message.warning(`当前文件${ parseInt(imgSize) }M,上传文件不能超过50M`)
                    return false
                }
            },
            onSubmit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var parms = {
                            id: this.lineForm.id,
                            schoolId: this.loginInfo.user.schoolId,
                            title: this.lineForm.name,
                            type: this.lineForm.ldfl,
                            img: this.lineForm.sjImage,
                            videoid: this.lineForm.fileid,
                            ldmb: this.lineForm.ldmb,
                            aqygz: this.lineForm.aqygz,
                            jtly: this.lineForm.jtly,
                            zzzb: this.lineForm.zzzb,
                            csygj: this.lineForm.csygj,
                            createUser: this.loginInfo.user.id,
                            jyzId: this.jyzid,
                            pfbzs: this.lineForm.domains
                        };
                        this.$api.jyz.addLdsj({
                            str: JSON.stringify(parms)
                        }).then(res => {
                            if (res.code == '0') {
                                this.$message.success('操作成功！');
                                this.$emit('update')
                            } else {
                                this.$message.error('操作失败！');
                            }
                        })
                    } else {
                        return false;
                    }
                });

            },
            progress(event) {
                this.showProgress = true;
                this.progInt = parseInt(event.loaded / event.total * 100, 10);
            },
            success(response, file, fileList) {
                console.log(response);
                this.showProgress = false;
                this.lineForm.sjVideoImage = response.body.data.firstframe;
                this.lineForm.fileName = response.body.data.fileName;
                this.lineForm.fileid = response.body.data.fileid;
                this.lineForm.url = response.body.data.url;
                this.$refs['image'].clearValidate()
            },
            beforeUpload(file) {
                const fileName = file.name;
                const index = fileName.lastIndexOf(".");
                const ext = fileName.substr(index + 1);
                const arr = ["mp4"];
                const isOk = arr.includes(ext);
                if (!isOk) {
                    this.$message.warning('视频格式暂不支持！');
                    return false;
                }
                var imgSize = file.size / (1024 * 1024);
                if (imgSize > 500) {
                    this.$message.warning(`当前文件${ parseInt(imgSize) }M,上传文件不能超过500M`)
                    return false
                }
            }
        }
    };
</script>

<style scoped lang="scss">
    .main-cont {
        position: relative;
        height: 100%;

        .posa {
            left: 0;
            bottom: 0;
            width: 100%;
            overflow-y: auto;
        }

    }

    .avatar-uploader {
        // width: 327px;
    }

    // /deep/ .el-upload{
    //     width: 100%;
    // }
    .upload-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 205px;
        height: 166px;
        background-color: #F0F1F8;
        line-height: 110px;
        color: #6872ff;
        font-size: 30px;
        border-radius: 10px;

        div {
            height: 20px;
            line-height: 20px;
            font-size: 10px;
            color: #a7abb1;

        }

        &:hover {
            color: #626BF1;

            div {
                color: #626BF1;
            }
        }
    }

    .item>>>.el-form-item__content {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    .avatar {
        width: 110px;
        height: 110px;
    }

    .item>>>.el-form-item__content {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    .avatar {
        width: 110px;
        height: 110px;
    }

    .bgf {
        height: 100%;
        background-color: #fff;
        overflow-y: auto;
    }

    .fm .img {
        border: 1px solid #ccc;

        &.active,
        &:hover {
            border: 1px solid #00aaff;
        }
    }


    /deep/ .submit .el-form-item__content {
        display: flex;
        align-items: center;
        justify-content: flex-end;
    }
</style>
